<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: 当燃
 * Date: 2015-09-09
 */
namespace Admin\Controller;
use Admin\Logic\OrderLogic;
use Think\AjaxPage;

class OrderController extends BaseController {
    public  $order_status;
    public  $shipping_status;
    public  $pay_status;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        C('TOKEN_ON',false); // 关闭表单令牌验证
        // 订单 支付 发货状态
        $this->order_status = C('ORDER_STATUS');
        $this->pay_status = C('PAY_STATUS');
        $this->shipping_status = C('SHIPPING_STATUS');
        $this->assign('order_status',$this->order_status);
        $this->assign('pay_status',$this->pay_status);
        $this->assign('shipping_status',$this->shipping_status);
    }

    /*
     *订单首页
     */
    public function index(){
        $begin = date('Y/m/d');//30天前
        $end = date('Y/m/d',time());
        $is_admin=session();
        $id=$is_admin['admin_id'];
        $roleid=M('admin')->field('role_id')->where("admin_id=$id")->find();
        $roleid=$roleid['role_id'];
        $storename=M('store')->where("roleid=$roleid")->select();
        $goods_class=M('goods_category')->where("level=3 and roleid=$roleid")->select();   
        $this->assign('goods_class',$goods_class);
        $this->assign('storename',$storename);
        $this->assign('timegap',$begin.'-'.$end);
        $this->display();
    }

    /*
     *Ajax首页
     */
    public function ajaxindex(){
        $orderLogic = new OrderLogic();       
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1])+86399;
        }
        // 搜索条件
        $condition = array();
        
        $consignee=I('consignee');
        $condition['consignee']=array('like',"%$consignee%");
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        
        I('store_id') ? $condition['store_id'] = (I('store_id')) : false;              
        I('order_sn') ? $condition['order_sn'] = trim(I('order_sn')) : false;
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        $pay_code=I('pay_code');
        $condition['pay_code']=array('like',"%$pay_code%");
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;


        $is_admin=session();

        $id=$is_admin['admin_id'];
        $roleid=M('admin')->field('role_id')->where("admin_id=$id")->find();
        $roleid=$roleid['role_id'];
        $condition['ty_order.roleid']=$roleid;
        /*增加理疗师筛选*/
        $tguser_input=I('tguser');
        $tguser = M('users')->query("select nickname,user_id  from __PREFIX__users where  group_id in(5,7)");
        $tguser_m = array();
        $tguser_n = array();
        foreach($tguser as $v){
            $tguser_m[$v['user_id']] = $v['nickname'];
            $tguser_n[$v['nickname']] = $v['user_id'];
        }
        $nn = in_array($tguser_input,$tguser_m);
        if($nn) {
            $tgid = $tguser_n[$tguser_input];
            $condition['tuiguangid'] = $tgid;
        }


        $sort_order = I('order_by','DESC').' '.I('sort');
       
        $doctor_input=I('doctor_id');

        $doctor = M('users')->query("select nickname,user_id  from __PREFIX__users where   group_id =8");
        $tdoctor_m = array();
        $doctor_n = array();
        foreach($doctor as $v){
            $doctor_m[$v['user_id']] = $v['nickname'];
            $doctor_n[$v['nickname']] = $v['user_id'];
        }
        $aa = in_array($doctor_input,$doctor_m);

        if($aa) {
            $doctorid = $doctor_n[$doctor_input];
            $condition['doctor_id'] = $doctorid;
        }
        $goods_class=I('goods_class');
        $goods_name=I('goods_name');

        if($goods_class){
            $goods=M('goods')->field('goods_id')->where(array('cat_id3'=>$goods_class))->select();
       
        }elseif($goods_name){
             $goods=M('goods')->field('goods_id')->where("goods_name like '%$goods_name%' ")->select();
        }else{
             $goods=M('goods')->field('goods_id')->select();
        }
         foreach ($goods as $v)
            {
                $v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串
                $temp[] = $v;
            }
            $t="";
            foreach($temp as $v){
                $t.="'".$v."'".",";
            }
            $t=substr($t,0,-1);

        $orde=M('order_goods')->field('order_id')->where("goods_id in ($t)")->select();
       
         foreach ($orde as $v)
            {
                $v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串
                $temp1[] = $v;
            }
            $t1="";
            foreach($temp1 as $v){
                $t1.=$v.",";
            }
            $t1=substr($t1,0,-1);

        $condition['order_id']=array('in',$t1);
        $count = M('order')->where($condition)->count();
        $Page  = new AjaxPage($count,20);
        $show = $Page->show();
        //获取订单列表
        $orderList = $orderLogic->getOrderList($condition,$sort_order,$Page->firstRow,$Page->listRows);
        
        $store_list = M('store')->getField('store_id,store_name'); 
        foreach ($orderList as &$v){
            $goods=$v['goods_name'];
            $goods_num=0;
            foreach($goods as $v1){ 
               $goods_num+=$v1['goods_num'];
            }
            $v['goods_num']=$goods_num;
            $sl+=$goods_num;
            $zj+=$v['total_amount'];
           if($v['order_status']=='6'){
                   
                    $ys1=$v['yajin'];
            }else{
                 $ys1=$v['total_amount'];
            }

            if($v['order_status']=='6'){
                    $qk1=$v['order_amount1'];
            }else{
                if($v['total_amount']==$v['order_amount1']){
                    $qk1=$v['yajin'];
                }else{
                    $qk1=$v['order_amount'];
                }
            }
            $ys+=$ys1;
            $qk+=$qk1;

        }
        $tj=array(
            'sl'=>$sl,
            'zj'=>$zj,
            'ys'=>$ys,
            'qk'=>$qk,
            );
        if($Page->firstRow =='0'){
        $a=1;
       }else{
        $a=$Page->firstRow+1;
       }
        $res = M('order')->where($condition)->order($order)->select();
        foreach($res as $k =>&$v){
            $v['total_price']=$v['goods_price'];
            $v['order_amount1']=$v['total_amount']-$v['yajin'];
        }
        $arr_sum1=array(); 
        $total_price = 0;
        $yajin = 0;
        $order_amount1=0;  

        foreach($res as $item){  
                $total_price +=  $item['total_amount'];
                $yajin +=  $item['yajin'];  
                $order_amount1 +=  $item['order_amount1'];  
        } 
        $order_status=I('order_status');
        $total_price=array('total_price'=>$total_price);
        $yajin=array('yajin'=>$yajin);
        $order_amount1=array('order_amount1'=>$order_amount1);
        $order_status=array('order_status'=>$order_status);
        $arr=array_merge($order_status,$total_price,$yajin,$order_amount1);
       $this->assign('a',$a);
       $this->assign('arr',$arr);
        $this->assign('store_list',$store_list);       
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
         $this->assign('tj',$tj);
        $this->display();
    }

    
    /*
     * ajax 发货订单列表
    */
    public function ajaxdelivery(){
        $orderLogic = new OrderLogic();
        $condition = array();
        I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
        I('order_sn') != '' ? $condition['order_sn'] = trim(I('order_sn')) : false;
        $condition['order_status'] = array('in','1,2,4');
        $shipping_status = I('shipping_status');
        $condition['shipping_status'] = empty($shipping_status) ? array('neq',1) : $shipping_status;        
        $count = M('order')->where($condition)->count();
        $Page  = new AjaxPage($count,10);
        //搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =   urlencode($val);
        }
        $show = $Page->show();
        $orderList = M('order')->where($condition)->limit($Page->firstRow.','.$Page->listRows)->order('add_time DESC')->select();
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
    /**
     * 订单详情
     * @param int $id 订单id
     */
    public function detail($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $button = $orderLogic->getOrderButton($order);
		//var_dump($button);
        // 获取操作记录
        $action_log = M('order_action')->where(array('order_id'=>$order_id))->order('log_time desc')->select();
        $yjjl=M('order_yajing')->where(array('order_id'=>$order_id))->select();
        $this->assign('order',$order);
        $this->assign('action_log',$action_log);
        $this->assign('orderGoods',$orderGoods);
        $split = count($orderGoods) >1 ? 1 : 0;
        foreach ($orderGoods as $val){
            if($val['goods_num']>1){
                $split = 1;
            }
        }
        $order_pay=M('order_pay')->where("order_id=$order_id")->select();
        $order_id1=I('order_id1');
        if($order_id1){
            $order_zs=M('order_goods')->where("order_id=$order_id1")->select();
             $this->assign('order_zs',$order_zs);
        }else{
            $order_sn=$order['order_sn'];
            $order1=M('order')->where("master_order_sn=$order_sn")->find();
            $id=$order1['order_id'];
            if($id){
                 $order_zs=M('order_goods')->where("order_id=$id")->select();
            $this->assign('order_zs',$order_zs);
            }
        }
        $this->assign('order_pay',$order_pay);
        $this->assign('yjjl',$yjjl);
        $this->assign('split',$split);
        $this->assign('button',$button);
        $this->display();
    }

    /**
     * 订单编辑
     * @param int $id 订单id
     */
    public function edit_order(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        } 
    
        $orderGoods = $orderLogic->getOrderGoods($order_id);
                
        if(IS_POST)
        {   
            M('order')->startTrans();
            $url = C('ERP_URL').'scm/invSo/updateInvSo?action=updateInvSo';
            $order['consignee'] = I('consignee');// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机           
            $order['invoice_title'] = I('invoice_title');// 发票
            $order['admin_note'] = I('admin_note'); // 管理员备注
            $order['admin_note'] = I('admin_note'); //                  
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');            
            $order['pay_code'] = I('payment');// 支付方式            
            $order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>I('payment')))->getField('name');                            
            $goods_id_arr = I("goods_id");
             $order['doctor_id']=I('doctor_id');
            $new_goods = $old_goods_arr = array();
            //################################订单添加商品
            if($goods_id_arr){
                $new_goods = $orderLogic->get_spec_goods($goods_id_arr);
                foreach($new_goods as $key => $val)
                {
                    $data3[$key]['invId']   =   $val['goods_sn'];
                    $data3[$key]['invNumber']   =  '';
                    $data3[$key]['invName']   =  '';
                    $data3[$key]['invSpec']   =  '';
                    $data3[$key]['invSpec']   =  -1;
                    $data3[$key]['skuName']   =  '';
                    $data3[$key]['unitId']   =  0;
                    $data3[$key]['mainUnit']   =  '';
                    $data3[$key]['qty']   =   $val['goods_num'];
                    $data3[$key]['price']   =   $val['zj'];
                    $data3[$key]['discountRate']   =   0;
                    $data3[$key]['deduction']   =   0;
                    $data3[$key]['amount']   =   $val['zj'];
                    $data3[$key]['locationId']   =   $roleid;
                    $data3[$key]['locationName'] = $role_info['user_name'];
                    $data3[$key]['description'] =   $order['admin_note'];
                    $val['order_id'] = $order_id;
                    $rec_id = M('order_goods')->add($val);//订单添加商品
                    if(!$rec_id)
                        $this->error('添加失败');
                }
            }
            
            //################################订单修改删除商品
            $old_goods = I('old_goods');
            $old_good=I('old_good');
            foreach ($orderGoods as $val){
                if(empty($old_goods[$val['rec_id']])){
                    M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
                }else{
                    //修改商品数量
                    if($old_goods[$val['rec_id']] != $val['goods_num']){
                        $val['goods_num'] = $old_goods[$val['rec_id']];
                        M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
                    }
                    $order_price=$old_good[$val['rec_id']]/$old_goods[$val['rec_id']];
                    $order_price1=round($order_price,2);
                    if($order_price1 !=$val['goods_price']){
                        $val['goods_price']=$order_price1;
                        $val['zj']=$old_good[$val['rec_id']];
                        $val['member_goods_price']=$order_price;
                        M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_price'=>$val['goods_price'],'member_goods_price'=>$val['member_goods_price']));
                    }
                    $old_goods_arr[] = $val;
                }

            }
            foreach($old_goods_arr as $key => $val){
                $data2[$key]['invId']   =   $val['goods_sn'];
                $data2[$key]['invNumber']   =  '';
                $data2[$key]['invName']   =  '';
                $data2[$key]['invSpec']   =  '';
                $data2[$key]['invSpec']   =  -1;
                $data2[$key]['skuName']   =  '';
                $data2[$key]['unitId']   =  0;
                $data2[$key]['mainUnit']   =  '';
                $data2[$key]['qty']   =   $val['goods_num'];
                $data2[$key]['price']   =   $val['zj'];
                $data2[$key]['discountRate']   =   0;
                $data2[$key]['deduction']   =   0;
                $data2[$key]['amount']   =   $val['zj'];
                $data2[$key]['locationId']   =   $roleid;
                $data2[$key]['locationName'] = $role_info['user_name'];
                $data2[$key]['description'] =   $order['admin_note'];
            }
            $goodsArr = array_merge($old_goods_arr,$new_goods);
            $data1['postData']['entries']   =   $goodsArr;
            $result = calculate_price($order['user_id'],$goodsArr,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],0,0,0,0);
            if($result['status'] < 0)
            {
                $this->error($result['msg']);
            }
       
            //################################修改订单费用
            $order['goods_price']    = $result['result']['goods_price']; // 商品总价
            $order['shipping_price'] = $result['result']['shipping_price'];//物流费
            $order['order_amount']   = $result['result']['order_amount']; // 应付金额
            $order['total_amount']   = $result['result']['total_amount']; // 订单总价           
            $o = M('order')->where('order_id='.$order_id)->save($order);
            $data1['postData']['id'] =   '-1';
            $data1['postData']['buId'] =   1;
            $data1['postData']['contactName'] =  $order['consignee'];
            $data1['postData']['salesId'] =  0;
            $data1['postData']['salesName'] =  '';
            $data1['postData']['date'] =  date("Y-m-d");
            $data1['postData']['deliveryDate'] =  date("Y-m-d");
            $data1['postData']['billNo'] =  $order['order_sn'];
            $data1['postData']['transType'] =   '150601';
            $data1['postData']['totalQty'] =   array_sum($number_count);
            $data1['postData']['totalDiscount'] =   0;
            $data1['postData']['totalAmount'] =   $order['order_amount'];
            $data1['postData']['description'] =   $order['admin_note'];
            $data1['postData']['disRate'] =   $order['give_integral']/$order['total_amount'];
            $data1['postData']['disAmount'] =   $order['total_amount']-$order['give_integral'];
            $data1['postData']['amount'] =   $order['give_integral'];
            $data1['postData']['billType'] =   'SALE';
            $data1['postData']['billDate'] =   date("Y-m-d");
            $data1['postData']['transTypeName'] =   '订货';
            $data1['postData']['totalTax'] =   0;
            $data1['postData']['totalTaxAmount'] =   0;
            $data1['postData']['uid'] =   $roleid;
            $data1['postData']['userName'] =   $role['user_name'];
            $data1['postData']['modifyTime'] =   date("Y-m-d H:i:s");
            $data1['postData']['deposit'] =   0;
            $data1['postData']['amountPaid'] =   0;
            if($data1['postData']['otherEntries']) $data1['postData']['otherEntries']  =   serialize($data1['postData']['otherEntries']);
            $admin_id = session('admin_id'); // 当前操作的管理员
            $l = $orderLogic->orderActionLog($order_id,'edit','修改订单',$admin_id);//操作日志
            $request = httpRequest($url,'POST',encryptDecrypt(C('KEY_ERP'),$data1,0));
            if($o && $l  && json_decode($request)->status == 200){
                M('order')->commit();
                $this->success('修改成功',U('Admin/Order/detail',array('order_id'=>$order_id)));
            }else{
                M('order')->rollback();
                $this->success('修改失败',U('Admin/Order/detail',array('order_id'=>$order_id)));
            }
            exit;

        }
        // 获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //获取订单城市
        $city =  M('region')->where(array('parent_id'=>$order['province'],'level'=>2))->select();
        //获取订单地区
        $area =  M('region')->where(array('parent_id'=>$order['city'],'level'=>3))->select();
        //获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        //获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
        $doctor = D('seller')->field('ty_users.nickname,ty_users.user_id')->join('ty_users on ty_seller.user_id= ty_users.user_id')->where(" ty_seller.group_id=8 and store_id=0 and is_admin=0 ")->select();
        $this->assign('doctor',$doctor);
        $this->assign('order',$order);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        $this->assign('orderGoods',$orderGoods);
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        $this->display();
    }
    
    /*
     * 拆分订单
     */
    public function split_order(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        }
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        if(IS_POST){
            $data = I('post.');
            //################################先处理原单剩余商品和原订单信息
            $old_goods = I('goods');
            foreach ($orderGoods as $val){
                if(empty($old_goods[$val['rec_id']])){
                    M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
                }else{
                    //修改商品数量
                    if($old_goods[$val['rec_id']] != $val['goods_num']){
                        $val['goods_num'] = $old_goods[$val['rec_id']];
                        M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
                    }
                    $oldArr[] = $val;//剩余商品
                }
                $all_goods[$val['rec_id']] = $val;//所有商品信息
            }
            $result = calculate_price($order['user_id'],$oldArr,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],0,0,0,0);
            if($result['status'] < 0)
            {
                $this->error($result['msg']);
            }
            //修改订单费用
            $res['goods_price']    = $result['result']['goods_price']; // 商品总价
            $res['order_amount']   = $result['result']['order_amount']; // 应付金额
            $res['total_amount']   = $result['result']['total_amount']; // 订单总价
            M('order')->where("order_id=".$order_id)->save($res);
            //################################原单处理结束
            
            //################################新单处理
            for($i=1;$i<20;$i++){
                if(empty($_POST[$i.'_goods'])){
                    break;
                }else{
                    $split_goods[] = $_POST[$i.'_goods'];
                }
            }

            foreach ($split_goods as $key=>$vrr){
                foreach ($vrr as $k=>$v){
                    $all_goods[$k]['goods_num'] = $v;
                    $brr[$key][] = $all_goods[$k];
                }
            }
            
            foreach($brr as $goods){
                $result = calculate_price($order['user_id'],$goods,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],0,0,0,0);
                if($result['status'] < 0)
                {
                    $this->error($result['msg']);
                }
                $new_order = $order;
                $new_order['order_sn'] = date('YmdHis').mt_rand(1000,9999);
                $new_order['parent_sn'] = $order['order_sn'];
                //修改订单费用
                $new_order['goods_price']    = $result['result']['goods_price']; // 商品总价
                $new_order['order_amount']   = $result['result']['order_amount']; // 应付金额
                $new_order['total_amount']   = $result['result']['total_amount']; // 订单总价
                $new_order['add_time'] = time();
                unset($new_order['order_id']);
                $new_order_id = M('order')->add($new_order);//插入订单表
                foreach ($goods as $vv){
                    $vv['order_id'] = $new_order_id;
                    $nid = M('order_goods')->add($vv);//插入订单商品表
                }
            }
            //################################新单处理结束
            $this->success('操作成功',U('Admin/Order/detail',array('order_id'=>$order_id)));
                exit;
        }
        
        foreach ($orderGoods as $val){
            $brr[$val['rec_id']] = array('goods_num'=>$val['goods_num'],'goods_name'=>getSubstr($val['goods_name'], 0, 35).$val['spec_key_name']);
        }
        $this->assign('order',$order);
        $this->assign('goods_num_arr',json_encode($brr));
        $this->assign('orderGoods',$orderGoods);
        $this->display();
    }
    
    /*
     * 价钱修改
     */
    public function editprice($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);

       
        $this->editable($order);
        if(IS_POST){
            $admin_id = session('admin_id');
            if(empty($admin_id)){
                $this->error('非法操作');
                exit;
            }
            $update['discount'] = I('post.discount');
            $update['shipping_price'] = I('post.shipping_price');
            $update['yajin2'] = I('post.yajin2');
            $update['yajin1'] = I('post.yajin1');
            $update['yajin']=$update['yajin1']+$update['yajin2'];
            $updatetime=I('post.updatetime');
            if($updatetime){
                $update['updatetime']=strtotime($updatetime);
            }else{
                 $update['updatetime']=time();
            }

            $update['order_amount'] = $order['goods_price'] + $update['shipping_price'] - $update['discount'] - $order['user_money'] - $order['integral_money'] - $order['coupon_price'] - $update['yajin'];
         
           if($order['goods_price']==$update['yajin'] ){
                $update['order_status']='1';
                 foreach($orderGoods as $k => $v){
                    $v['give_integral']=$v['give_integral']*$v['goods_num'];
                    accountLog($order['user_id'], 0,$v['give_integral'],"下单赠送积分");
                }
           }

            $row = M('order')->where(array('order_id'=>$order_id))->save($update);
            if(!$row){
                $this->success('没有更新数据',U('Admin/Order/editprice',array('order_id'=>$order_id)));
            }else{
                $update['order_id']=$order_id;
                $update['store_id']=$order['store_id'];
                $update['yajing']=$_POST['yajin2'];
                $update['status']='1';
                M('order_yajing')->add($update);
                $this->success('操作成功',U('Admin/Order/detail',array('order_id'=>$order_id)));
            }
            exit;
        }
        $this->assign('order',$order);
        $this->display();
    }

    /**
     * 订单删除
     * @param int $id 订单id
     */
    public function delete_order($order_id){
        $orderLogic = new OrderLogic();
        $del = $orderLogic->delOrder($order_id);
        if($del){
            $this->success('删除订单成功');
        }else{
            $this->error('订单删除失败');
        }
    }
    
    /**
     * 订单取消付款
     */
    public function pay_cancel($order_id){
        if(I('remark')){
            $data = I('post.');
            $note = array('退款到用户余额','已通过其他方式退款','不处理，误操作项');
		
            if($data['refundType'] == 0 && $data['amount']>0){
				accountLoga($data['user_id'], $data['amount'], $data['pay_points'],  '退款到用户余额');
            }
			//$sql=M('users')->where()->find();
			//var_dump($sql);
            $orderLogic = new OrderLogic();
            $admin_id = session('admin_id'); // 当前操作的管理员
            $d = $orderLogic->orderActionLog($data['order_id'],'pay_cancel',$data['remark'].':'.$note[$data['refundType']],$admin_id);
            if($d){
                exit("<script>window.parent.pay_callback(1);</script>");
            }else{
                exit("<script>window.parent.pay_callback(0);</script>");
            }
        }else{
            $order = M('order')->join('ty_order_goods on ty_order.order_id=ty_order_goods.order_id')->where("ty_order.order_id=$order_id")->find();
			$this->assign('order',$order);
            $this->display();
        }
    }

    /**
     * 订单打印
     * @param int $id 订单id
     */
    public function order_print($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $order['province'] = getRegionName($order['province']);
        $order['city'] = getRegionName($order['city']);
        $order['district'] = getRegionName($order['district']);
        $order['full_address'] = $order['province'].' '.$order['city'].' '.$order['district'].' '. $order['address'];
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $shop = tpCache('shop_info');
        $this->assign('order',$order);
        $this->assign('shop',$shop);
        $this->assign('orderGoods',$orderGoods);
        $this->display('print');
    }

    /**
     * 快递单打印
     */
    public function shipping_print(){
        $order_id = I('get.order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        //查询是否存在订单及物流
        $shipping = M('plugin')->where(array('code'=>$order['shipping_code'],'type'=>'shipping'))->find();        
        if(!$shipping){
            $this->error('物流插件不存在');
        }
        if(empty($shipping['config_value'])){
            $this->error('请设置'.$shipping['name'].'打印模板');
        }
        $shop = tpCache('shop_info');//获取网站信息
        $shop['province'] = empty($shop['province']) ? '' : getRegionName($shop['province']);
        $shop['city'] = empty($shop['city']) ? '' : getRegionName($shop['city']);
        $shop['district'] = empty($shop['district']) ? '' : getRegionName($shop['district']);

        $order['province'] = getRegionName($order['province']);
        $order['city'] = getRegionName($order['city']);
        $order['district'] = getRegionName($order['district']);
        if(empty($shipping['config'])){
            $config = array('width'=>840,'height'=>480,'offset_x'=>0,'offset_y'=>0);
            $this->assign('config',$config);
        }else{
            $this->assign('config',unserialize($shipping['config']));
        }
        $template_var = array("发货点-名称", "发货点-联系人", "发货点-电话", "发货点-省份", "发货点-城市",
                 "发货点-区县", "发货点-手机", "发货点-详细地址", "收件人-姓名", "收件人-手机", "收件人-电话", 
                "收件人-省份", "收件人-城市", "收件人-区县", "收件人-邮编", "收件人-详细地址", "时间-年", "时间-月", 
                "时间-日","时间-当前日期","订单-订单号", "订单-备注","订单-配送费用");
        $content_var = array($shop['store_name'],$shop['contact'],$shop['phone'],$shop['province'],$shop['city'],
            $shop['district'],$shop['phone'],$shop['address'],$order['consignee'],$order['mobile'],$order['phone'],
            $order['province'],$order['city'],$order['district'],$order['zipcode'],$order['address'],date('Y'),date('M'),
            date('d'),date('Y-m-d'),$order['order_sn'],$order['admin_note'],$order['shipping_price'],
        );
        $shipping['config_value'] = str_replace($template_var,$content_var, $shipping['config_value']);
        $this->assign('shipping',$shipping);
        $this->display("Plugin/print_express");
    }

    /**
     * 生成发货单
     */
    public function deliveryHandle(){
        $orderLogic = new OrderLogic();
        $data = I('post.');
        $res = $orderLogic->deliveryHandle($data);
        if($res){
            $this->success('操作成功',U('Admin/Order/delivery_info',array('order_id'=>$data['order_id'])));
        }else{
            $this->success('操作失败',U('Admin/Order/delivery_info',array('order_id'=>$data['order_id'])));
        }
    }

    
    public function delivery_info(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $this->assign('order',$order);
        $this->assign('orderGoods',$orderGoods);
        $delivery_record = M('delivery_doc')->join('LEFT JOIN __SELLER__ ON __SELLER__.seller_id = __DELIVERY_DOC__.admin_id')->where('order_id='.$order_id)->select();
        $this->assign('delivery_record',$delivery_record);//发货记录
        $this->display();
    }
    
    /**
     * 发货单列表
     */
    public function delivery_list(){
        $this->display();
    }
    
    /*
     * ajax 退货订单列表
     */
    public function ajax_return_list(){
        // 搜索条件        
        $order_sn =  trim(I('order_sn'));
        $order_by = I('order_by') ? I('order_by') : 'id';
        $sort_order = I('sort_order') ? I('sort_order') : 'desc';
        $status =  I('status');
        
        $where = " 1 = 1 ";
        $order_sn && $where.= " and order_sn like '%$order_sn%' ";
        empty($order_sn) && $where.= " and status = '$status' ";
        $count = M('return_goods')->where($where)->count();
        $Page  = new AjaxPage($count,13);
        $show = $Page->show();
        $list = M('return_goods')->where($where)->order("$order_by $sort_order")->limit("{$Page->firstRow},{$Page->listRows}")->select();        
        $goods_id_arr = get_arr_column($list, 'goods_id');
        if(!empty($goods_id_arr))
            $goods_list = M('goods')->where("goods_id in (".implode(',', $goods_id_arr).")")->getField('goods_id,goods_name');
        $store_list = M('store')->getField('store_id,store_name');        
        $this->assign('store_list',$store_list);
        $this->assign('goods_list',$goods_list);
        $this->assign('list',$list);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
    /**
     * 删除某个退换货申请
     */
    public function return_del(){
        $id = I('get.id');
        M('return_goods')->where("id = $id")->delete(); 
        $this->success('成功删除!');
    }
    /**
     * 退换货操作
     */
    public function return_info()
    {
        $id = I('id');
        $return_goods = M('return_goods')->where("id= $id")->find();
        if($return_goods['imgs'])            
             $return_goods['imgs'] = explode(',', $return_goods['imgs']);
        $user = M('users')->where("user_id = {$return_goods[user_id]}")->find();
        $goods = M('goods')->where("goods_id = {$return_goods[goods_id]}")->find();
        $type_msg = array('退换','换货');
        $status_msg = array('未处理','处理中','已完成');
        if(IS_POST)
        {
            $data['type'] = I('type');
            $data['status'] = I('status');
            $data['remark'] = I('remark');                                    
            $note ="退换货:{$type_msg[$data['type']]}, 状态:{$status_msg[$data['status']]},处理备注：{$data['remark']}";
            $result = M('return_goods')->where("id= $id")->save($data);    
            if($result)
            {        
                $type = empty($data['type']) ? 2 : 3;
                $where = " order_id = ".$return_goods['order_id']." and goods_id=".$return_goods['goods_id'];
                M('order_goods')->where($where)->save(array('is_send'=>$type));//更改商品状态        
                $orderLogic = new OrderLogic();
                $admin_id = session('admin_id'); // 当前操作的管理员
                $log = $orderLogic->orderActionLog($return_goods[order_id],'refund',$note,$admin_id);
                $this->success('修改成功!');            
                exit;
            }  
        }        
        
        $this->assign('id',$id); // 用户
        $this->assign('user',$user); // 用户
        $this->assign('goods',$goods);// 商品
        $this->assign('return_goods',$return_goods);// 退换货               
        $this->display();
    }
    
    /**
     * 管理员生成申请退货单
     */
    public function add_return_goods()
   {                
            $order_id = I('order_id'); 
            $goods_id = I('goods_id');
                
            $return_goods = M('return_goods')->where("order_id = $order_id and goods_id = $goods_id")->find();            
            if(!empty($return_goods))
            {
                $this->error('已经提交过退货申请!',U('Admin/Order/return_list'));
                exit;
            }
            $order = M('order')->where("order_id = $order_id")->find();
            
            $data['order_id'] = $order_id; 
            $data['order_sn'] = $order['order_sn']; 
            $data['goods_id'] = $goods_id; 
            $data['addtime'] = time(); 
            $data['user_id'] = $order[user_id];            
            $data['remark'] = '管理员申请退换货'; // 问题描述            
            M('return_goods')->add($data);            
            $this->success('申请成功,现在去处理退货',U('Admin/Order/return_list'));
            exit;
    }

    /**
     * 订单操作
     * @param $id
     */
    public function order_action(){     
        $orderLogic = new OrderLogic();
        $action = I('get.type');
        $order_id = I('get.order_id');
        if($action && $order_id){
             $a = $orderLogic->orderProcessHandle($order_id,$action);           
             $admin_id = session('admin_id'); // 当前操作的管理员            
             $res = $orderLogic->orderActionLog($order_id,$action,I('note'),$admin_id);
             if($res && $a){
                exit(json_encode(array('status' => 1,'msg' => '操作成功')));
             }else{
                exit(json_encode(array('status' => 0,'msg' => '操作失败')));
             }
        }else{
            $this->error('参数错误',U('Admin/Order/detail',array('order_id'=>$order_id)));
        }
    }
    
    public function order_log(){
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1])+86399;
        }
        $condition = array();
        $log =  M('order_action');
        if($begin && $end){
            $condition['log_time'] = array('between',"$begin,$end");
        }
        $admin_id = I('admin_id');
        if($admin_id >0 ){
            $condition['action_user'] = $admin_id;
        }
        $count = $log->where($condition)->count();
        $Page = new \Think\Page($count,20);
        foreach($condition as $key=>$val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $show = $Page->show();
        $list = $log->where($condition)->order('action_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('list',$list);
        $this->assign('page',$show);    
        $admin = M('admin')->getField('admin_id,user_name');
        $this->assign('admin',$admin);      
        $this->display();
    }

    /**
     * 检测订单是否可以编辑
     * @param $order
     */
    private function editable($order){
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        }
        return;
    }

    public function export_order()
    {
        //搜索条件
        $where = 'where 1=1 ';
        $consignee = I('consignee');
        if($consignee){
            $where .= "AND consignee like '%$consignee%' ";
        }
        $order_sn =  I('order_sn');
        if($order_sn){
            $where .= "AND order_sn = '$order_sn' ";
        }
        if(I('order_status')){
            $where .= "AND order_status = ".I('order_status');
        }
        $store_id=I('store_id');
        if($store_id){
            $where .= "AND store_id = '$store_id' ";
        }
        $goods_class=I('goods_class');
        $goods_name=I('goods_name');
        $is_admin=session();
        $id=$is_admin['admin_id'];
        $roleid=M('admin')->field('role_id')->where("admin_id=$id")->find();
        $roleid=$roleid['role_id'];
        $where.="AND  ty_order.roleid=$roleid";
        if($goods_class){
            $goods=M('goods')->field('goods_id')->where(array('cat_id3'=>$goods_class))->select();
       
        }elseif($goods_name){
             $goods=M('goods')->field('goods_id')->where(array('goods_name'=>$goods_name))->select();
        }else{
            $goods=M('goods')->field('goods_id')->select();
        }
         foreach ($goods as $v)
            {
                $v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串
                $temp[] = $v;
            }
            $t="";
            foreach($temp as $v){
                $t.="'".$v."'".",";
            }
            $t=substr($t,0,-1);

             $orde=M('order_goods')->field('order_id')->where("goods_id in ($t)")->select();
         foreach ($orde as $v)
            {
                $v = join(",",$v); //可以用implode将一维数组转换为用逗号连接的字符串
                $temp1[] = $v;
            }
            $t1="";
            foreach($temp1 as $v){
                $t1.=$v.",";
            }
            $t1=substr($t1,0,-1);
            if($t1){
                $where .= " AND order_id in ($t1)";
            }
            if($tguser_input){
            $tguser = M('users')->query("select nickname,user_id  from __PREFIX__users where seller_id =".STORE_ID." and  group_id in(5,7)");
            $tguser_m = array();
            $tguser_n = array();
            foreach($tguser as $v){
                $tguser_m[$v['user_id']] = $v['nickname'];
                $tguser_n[$v['nickname']] = $v['user_id'];
            }
            $nn = in_array($tguser_input,$tguser_m);
            if($nn) {
                $tgid = $tguser_n[$tguser_input];
                $where .= " AND tuiguangid = ".$tgid;
            }
        }
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1])+86399;
            $where .= " AND `add_time`>'".$begin."' and `add_time` <'".$end."'";
        }
   
    $region = M('region')->getField('id,name');
                
    $sql = "select *,FROM_UNIXTIME(add_time,'%Y-%m-%d') as create_time from __PREFIX__order $where order by order_id";
        $orderList = D()->query($sql);   
        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">会员名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">购买数量</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">总金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">已付金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">欠款金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">理疗师</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">医生</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付方式</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">发药状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">下单时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">店铺</td>';
        $strTable .= '</tr>';
        
        foreach($orderList as $k=>$val){

            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].': '.$val['mobile'].' </td>';
            $orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
            $strGoods="";
            foreach($orderGoods as $goods){
                $strGoods .= " 商品名称：".$goods['goods_name'];
                if ($goods['spec_key_name'] != '') $strGoods .= " 规格：".$goods['spec_key_name'];
                $strGoods .= "<br />";
            }
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$strGoods.' </td>';
            $goods_num=0;
            foreach($orderGoods as $goods){
               $goods_num+=$goods['goods_num'];
            }
            unset($orderGoods);
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$goods_num.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['total_amount'].'</td>';
            if($val['yajin']=='0.00'&&$val['order_status']=='6'){
                $qian='0';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$qian.'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_amount'].'</td>';
            }elseif($val['order_status']=='6'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['yajin'].'</td>';
                $qian=$val['total_amount']-$val['yajin'];
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$qian.'</td>';
            }else{
                $qian='0';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_amount'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$qian.'</td>';
            }
            if($val['order_status']=='0'){
                 $strTable .= '<td style="text-align:left;font-size:12px;">'.待确认.'</td>';
            }elseif($val['order_status']=='1'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已确认.'</td>';
            }elseif($val['order_status']=='2'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已收货.'</td>';
            }elseif($val['order_status']=='3'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已取消.'</td>';
            }elseif($val['order_status']=='4'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已完成.'</td>';
            }elseif($val['order_status']=='5'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已作废.'</td>';
            }elseif($val['order_status']=='6'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.部分支付.'</td>';
            }elseif($val['order_status']=='7'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.积分兑换.'</td>';
            }elseif($val['order_status']=='8'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已退款.'</td>';
            }elseif($val['order_status']=='9'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.赠送.'</td>';
            }
            if($val['order_status']=='6'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.欠款.'</td>';
            }else{
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$this->pay_status[$val['pay_status']].'</td>';
            }
            
            $tguserid = $val['tuiguangid'];
            $tguserinfo = M('users')->where('user_id='.$tguserid)->find(); 
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$tguserinfo['nickname'].'</td>';    
            
            $doctor_id = $val['doctor_id'];
            $doctor_id = M('users')->where('user_id='.$doctor_id)->find(); 
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$doctor_id['nickname'].'</td>'; 
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['pay_name'].'</td>'; 
            if($val['shipping_status']=='0'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.未发货.'</td>';
            }elseif($val['shipping_status']=='1'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.已发货.'</td>';
            }elseif($val['shipping_status']=='1'){
                $strTable .= '<td style="text-align:left;font-size:12px;">'.部分发货.'</td>';
            }
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['create_time'].'</td>';
            $store_id=M('store')->field('store_name')->where('store_id='.$val['store_id'])->find();
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$store_id['store_name'].'</td>';
            $strTable .= '</tr>';
        }
        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'order');
        exit();
    }
    
    /**
     * 退货单列表
     */
    public function return_list(){
        $this->display();
    }
    
    /**
     * 添加一笔订单
     */
    public function add_order()
    {   
        
        $order = array();
        //  获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //  获取订单城市
        $city =  M('region')->where(array('parent_id'=>$order['province'],'level'=>2))->select();
        //  获取订单地区
        $area =  M('region')->where(array('parent_id'=>$order['city'],'level'=>3))->select();
        //  获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
        //  获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        $is_admin=session();
        $id=$is_admin['admin_id'];
        $roleid=M('admin')->field('role_id')->where("admin_id=$id")->find();
        $roleid=$roleid['role_id'];
        //  获取医生
        $doctor = D('seller')->field('ty_users.nickname,ty_users.user_id')->join('ty_users on ty_seller.user_id= ty_users.user_id')->where(" ty_seller.group_id=8 and store_id=0 and is_admin=0  and ty_users.roleid=$roleid ")->select();
        $admin = session();
       
        $role = M('admin')->field('role_id')->where(array('admin_id'=>$admin['admin_id']))->find();
        $role_info = M('admin')->where(array('admin_id'=>$admin['admin_id']))->find();
        $user_id=I('user_id');
        $user=M('users')->where(array('user_id'=>$user_id))->find();
        $tgt_id=$user['tuixiao_id'];
        $tgy=M('users')->where(array('user_id'=>$tgt_id))->find();
        $dp=$user['seller_id'];
        $dp1=M('store')->where(array('store_id'=>$dp))->find();

        if(IS_POST)
        {

            $order['user_id'] = I('user_id');// 用户id 可以为空
            $order['consignee'] = I('consignee');// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机           
            $order['invoice_title'] = I('invoice_title');// 发票
            $order['admin_note'] = I('admin_note'); // 管理员备注            
            $order['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
            $order['admin_note'] = I('admin_note'); // 
            $add_time=$_POST['add_time'];
            if($add_time){
                $order['add_time'] = strtotime($add_time);// 
            }else{
                 $order['add_time'] = time(); 
            }
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');            
            $zj=I('zj');
            $a=array_filter($zj);
            $payment=array_keys($a);
            $pay_name=array();
            foreach($payment as $v){
                $pay_name[]=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$v))->getField('name');
                
            }
            $pay_name=implode(",", $pay_name);
            $payment=implode(",", $payment);
            $order['pay_code']=$payment;   
            $order['pay_name']=$pay_name;             
            $order['yajin']=I('yajin');
            $order['doctor_id']=I('doctor_id');
            
            $yajin=I('yajin');
            if(empty($yajin)){
                $order['order_status']='1';
            }else{
                $order['order_status']='6';
            }
            
            $order['pay_status']='1';
            $order['shipping_status']='0';                
            $goods_id_arr = I("goods_id");
            $orderLogic = new OrderLogic();
            $order_goods = $orderLogic->get_spec_goods($goods_id_arr);   
            $goods=I("goods_id1");
            $order_goods1 = $orderLogic->get_spec_goods($goods);
            $result = calculate_price($order['user_id'],$order_goods,$order['shipping_code'],0,$order[province],$order[city],$order[district],0,0,0,0); 
                
            if($result['status'] < 0)   
            {
                 $this->error($result['msg']);      
            } 
           

          

           $order['roleid'] = $role['role_id']; //地区id 
           $tgid1=I('tguser_id1'); //推广id
           if($tgid1){
            $order['tuiguangid']=$tgid1;
           }else{
            $order['tuiguangid']=I('tguser_id');
           }
           $store_id1=I('store_id1'); //推广id
           if($store_id1){
            $order['store_id']=$store_id1;
           }else{
            $order['store_id']=I('store_id');
           }
           $order['goods_price']    = $result['result']['goods_price']; // 商品总价
           $order['shipping_price'] = $result['result']['shipping_price']; //物流费
           $order['order_amount']   = $result['result']['order_amount']; // 应付金额
           $order['total_amount']   = $result['result']['total_amount']; // 订单总价
           $order['give_integral']   = $result['result']['give_integral']; // 订单总积分
          
           $pay_points=M('users')->where(array('user_id'=>I('user_id')))->getField('pay_points');

            
           $url = C('ERP_URL').'scm/invSo/addNew?action=addNew';
           if($order['pay_code']=='jifen'){
                if($pay_points >= $order['give_integral']){
                     $order['order_status']='7';
                    // 添加订单
                    $order_id = M('order')->add($order);
                    if($order_id){
                        foreach($order_goods as $key => $val){
                            $val['order_id'] = $order_id;
                            $val['store_id'] = $order['store_id'];
                            $number_count[$key] =   $val['goods_num'];
                            $data1['postData']['entries'][$key]['invId']   =   $val['goods_sn'];
                            $data1['postData']['entries'][$key]['invNumber']   =  '';
                            $data1['postData']['entries'][$key]['invName']   =  '';
                            $data1['postData']['entries'][$key]['invSpec']   =  '';
                            $data1['postData']['entries'][$key]['invSpec']   =  -1;
                            $data1['postData']['entries'][$key]['skuName']   =  '';
                            $data1['postData']['entries'][$key]['unitId']   =  0;
                            $data1['postData']['entries'][$key]['mainUnit']   =  '';
                            $data1['postData']['entries'][$key]['qty']   =   $val['goods_num'];
                            $data1['postData']['entries'][$key]['price']   =   $val['zj'];
                            $data1['postData']['entries'][$key]['discountRate']   =   0;
                            $data1['postData']['entries'][$key]['deduction']   =   0;
                            $data1['postData']['entries'][$key]['amount']   =   $val['zj'];
                            $data1['postData']['entries'][$key]['locationId']   =   $roleid;
                            $data1['postData']['entries'][$key]['locationName'] = $role_info['user_name'];
                            $data1['postData']['entries'][$key]['description'] =   $order['admin_note'];
                            $val['give_integral']=$val['give_integral'];
                            accountLoga($order['user_id'], 0,$val['give_integral'],"积分兑换商品");
                            $rec_id = M('order_goods')->add($val);
                            if(!$rec_id)                 
                            $this->error('添加失败');                                  
                        }
                        $data1['postData']['id'] =   '-1';
                        $data1['postData']['buId'] =   1;
                        $data1['postData']['contactName'] =  $order['consignee'];
                        $data1['postData']['salesId'] =  0;
                        $data1['postData']['salesName'] =  '';
                        $data1['postData']['date'] =  date("Y-m-d");
                        $data1['postData']['deliveryDate'] =  date("Y-m-d");
                        $data1['postData']['billNo'] =  $order['order_sn'];
                        $data1['postData']['transType'] =   '150601';
                        $data1['postData']['totalQty'] =   array_sum($number_count);
                        $data1['postData']['totalDiscount'] =   0;
                        $data1['postData']['totalAmount'] =   $order['order_amount'];
                        $data1['postData']['description'] =   $order['admin_note'];
                        $data1['postData']['disRate'] =   $order['give_integral']/$order['total_amount'];
                        $data1['postData']['disAmount'] =   $order['total_amount']-$order['give_integral'];
                        $data1['postData']['amount'] =   $order['give_integral'];
                        $data1['postData']['billType'] =   'SALE';
                        $data1['postData']['billDate'] =   date("Y-m-d");
                        $data1['postData']['transTypeName'] =   '订货';
                        $data1['postData']['totalTax'] =   0;
                        $data1['postData']['totalTaxAmount'] =   0;
                        $data1['postData']['uid'] =   $roleid;
                        $data1['postData']['userName'] =   $role['user_name'];
                        $data1['postData']['modifyTime'] =   date("Y-m-d H:i:s");
                        $data1['postData']['deposit'] =   0;
                        $data1['postData']['amountPaid'] =   0;
                        if($data1['postData']['otherEntries']) $data1['postData']['otherEntries']  =   serialize($data1['postData']['otherEntries']);
                        $request = httpRequest($url,'POST',encryptDecrypt(C('KEY_ERP'),$data1,0));
                        accountLoga($order['user_id'], 0,$order['give_integral'],"积分兑换商品");
                        if(json_decode($request)->status == 200){
                            M('order')->commit();
                            $this->success('添加商品成功',U("Admin/Order/index",array('order_id'=>$order_id)));
                            exit();
                        }else{
                            M('order')->rollback();
                            $this->error('添加失败');
                        }    
                    }else{
                        $this->error('添加失败');
                    }                
                }else{
                    $this->error('积分不足,兑换失败');
                }
           }else{
                    M('order')->startTrans();
                    $order_id = M('order')->add($order);

                    foreach($a as$k => $v1){
                        $pay_name=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$k))->getField('name');
                        M('order_pay')->add(array('order_id'=>$order_id,'pay_name'=>$pay_name,'jinen'=>$v1));
                    }
                    if($order_id){
                        if($order_goods1){
                        $order_sn=M('order')->where("order_id=$order_id")->find();
                        $data['master_order_sn']=$order_sn['order_sn'];
                        $data['user_id']=$order['user_id'];
                        $data['order_status']='9';
                        $data['mobile']=$order['mobile'];// 手机  
                        $data['consignee']=$order['consignee'];
                        $data['add_time']=$order['add_time'];
                        $data['store_id']=$order['store_id'];;
                        $data['roleid']=$role['role_id'];
                        $tgid1=I('tguser_id1'); //推广id
                       if($tgid1){
                        $data['tuiguangid']=$tgid1;
                       }else{
                        $data['tuiguangid']=I('tguser_id');
                       }
                        $data['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
                        $or=M('order')->add($data);
                        if($or){
                            foreach($order_goods1 as $v){
                                $v['order_id'] = $or;
                                $v['store_id'] = $order['store_id'];
                                $rec_id = M('order_goods')->add($v);
                            }
                            foreach($order_goods1 as $key => $val){
                                $data1['postData']['otherEntries'][$key]['giveGoodsSn']     =   $val['goods_sn'];
                                $data1['postData']['otherEntries'][$key]['giveGoodsNum']    =   $val['goods_num'];
                            }
                        }
                    }
                        foreach($order_goods as $key => $val){
                            $val['order_id'] = $order_id;
                            $number_count[$key] =   $val['goods_num'];
                            $data1['postData']['entries'][$key]['invId']   =   $val['goods_sn'];
                            $data1['postData']['entries'][$key]['invNumber']   =  '';
                            $data1['postData']['entries'][$key]['invName']   =  '';
                            $data1['postData']['entries'][$key]['invSpec']   =  '';
                            $data1['postData']['entries'][$key]['invSpec']   =  -1;
                            $data1['postData']['entries'][$key]['skuName']   =  '';
                            $data1['postData']['entries'][$key]['unitId']   =  0;
                            $data1['postData']['entries'][$key]['mainUnit']   =  '';
                            $data1['postData']['entries'][$key]['qty']   =   $val['goods_num'];
                            $data1['postData']['entries'][$key]['price']   =   $val['zj'];
                            $data1['postData']['entries'][$key]['discountRate']   =   0;
                            $data1['postData']['entries'][$key]['deduction']   =   0;
                            $data1['postData']['entries'][$key]['amount']   =   $val['zj'];
                            $data1['postData']['entries'][$key]['locationId']   =   $roleid;
                            $data1['postData']['entries'][$key]['locationName'] = $role_info['user_name'];
                            $data1['postData']['entries'][$key]['description'] =   $order['admin_note'];
                            //$data1['postData']['invId']
                             if($order['order_status']!='6'){
                                $val['give_integral']=$val['give_integral'];
                                accountLog($order['user_id'], 0,$val['give_integral'],"下单赠送积分");
                            }
                            $rec_id = M('order_goods')->add($val);
                            if($yajin){
                                $val['yajing']=$yajin;
                                $val['store_id'] = $order['store_id'];
                                $val['updatetime']=$order['add_time'];
                                $val['status']=0;
                                M('order_yajing')->add($val);
                            }
                            if(!$rec_id)                 
                            $this->error('添加失败');                                  
                        }

                        $data1['postData']['id'] =   '-1';
                        $data1['postData']['buId'] =   1;
                        $data1['postData']['contactName'] =  $order['consignee'];
                        $data1['postData']['salesId'] =  0;
                        $data1['postData']['salesName'] =  '';
                        $data1['postData']['date'] =  date("Y-m-d");
                        $data1['postData']['deliveryDate'] =  date("Y-m-d");
                        $data1['postData']['billNo'] =  $order['order_sn'];
                        $data1['postData']['transType'] =   '150601';
                        $data1['postData']['totalQty'] =   array_sum($number_count);
                        $data1['postData']['totalDiscount'] =   0;
                        $data1['postData']['totalAmount'] =   $order['order_amount'];
                        $data1['postData']['description'] =   $order['admin_note'];
                        $data1['postData']['disRate'] =   $order['give_integral']/$order['total_amount'];
                        $data1['postData']['disAmount'] =   $order['total_amount']-$order['give_integral'];
                        $data1['postData']['amount'] =   $order['give_integral'];
                        $data1['postData']['billType'] =   'SALE';
                        $data1['postData']['billDate'] =   date("Y-m-d");
                        $data1['postData']['transTypeName'] =   '订货';
                        $data1['postData']['totalTax'] =   0;
                        $data1['postData']['totalTaxAmount'] =   0;
                        $data1['postData']['uid'] =   $roleid;
                        $data1['postData']['userName'] =   $role['user_name'];
                        $data1['postData']['modifyTime'] =   date("Y-m-d H:i:s");
                        $data1['postData']['deposit'] =   0;
                        $data1['postData']['amountPaid'] =   0;
                        if($data1['postData']['otherEntries']) $data1['postData']['otherEntries']  =   serialize($data1['postData']['otherEntries']);
 
                        $request = httpRequest($url,'POST',encryptDecrypt(C('KEY_ERP'),$data1,0));
                        if(json_decode($request)->status == 200){
                            M('order')->commit();
                            $this->success('添加商品成功',U("Admin/Order/index",array('order_id'=>$order_id)));
                            exit();
                        }else{
                            M('order')->rollback();
                            $this->error('添加失败');
                        }
                    }else{
                        $this->error('添加失败');
                    }                
                }
        }     
        $storename = M('store')->field('store_id,store_name')->where(array('roleid'=> $role['role_id']))->select(); 

        $this->assign('storename',$storename); 
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        $this->assign('user',$user);  
        $this->assign('doctor',$doctor); 
        $this->assign('tgy',$tgy);
        $this->display();
    }
    
    /**
     * 选择搜索商品
     */
    public function search_goods()
    {
        //$brandList =  M("brand")->select();
        $categoryList =  M("goods_category")->select();

        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);      
        $where = ' is_on_sale = 1 ';//搜索条件
        I('intro')  && $where = "$where and ".I('intro')." = 1";
        $cate_id = I('cat_id');

        if(I('cat_id')){
            $this->assign('cate_id',I('cat_id'));            
            $goods_category = M('goods_category')->where("cate_id = $cate_id")->find();
            $where = " $where  and cat_id{$goods_category['level']} = $cate_id "; // 初始化搜索条件   
        }

        if(I('brand_id')){
            $this->assign('brand_id',I('brand_id'));
            $where = "$where and brand_id = ".I('brand_id');
        }
        if(!empty($_REQUEST['keywords']))
        {
            $this->assign('keywords',I('keywords'));
            $where = "$where and (goods_name like '%".I('keywords')."%' or keywords like '%".I('keywords')."%')" ;
        } 
        $is_admin=session();
        $id=$is_admin['admin_id'];
        $roleid=M('admin')->field('role_id')->where("admin_id=$id")->find();
        $roleid=$roleid['role_id'];
        $where="$where and ty_goods.roleid=$roleid";

        $goodsList = M('goods')->where($where)->order('goods_id DESC')->limit(10)->select();

        foreach($goodsList as $key => $val)
        {
            $spec_goods = M('spec_goods_price')->where("goods_id = {$val['goods_id']}")->select();
            $goodsList[$key]['spec_goods'] = $spec_goods;            
        }
        $this->assign('goodsList',$goodsList);
        $this->display();        
    }
    
    public function ajaxOrderNotice(){
        $order_amount = M('order')->where(array('order_status'=>0))->count();
        echo $order_amount;
    }
    public function fahuo(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $delivery_record = M('delivery_doc')->join('LEFT JOIN __SELLER__ ON __SELLER__.seller_id = __DELIVERY_DOC__.admin_id')->where('order_id='.$order_id)->select();
        if($delivery_record){
            $order['invoice_no'] = $delivery_record[count($delivery_record)-1]['invoice_no'];
        }
        $this->assign('order',$order);
        $this->assign('orderGoods',$orderGoods);
        $this->assign('delivery_record',$delivery_record);//发货记录
        $this->display();
    }
    public function fahuo_add(){
        $order_id=$_POST['order_id'];   
        $shipping_status=$_POST['shipping_status'];
        $order=M('order')->where("order_id=$order_id")->save(array('shipping_status'=>$shipping_status));
        if($order){
            $this->success('操作成功',U('Order/index'));
        }else{
            $this->success('操作失败',U('Order/index'));
        }
    }
      public function fayao_print(){
        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $this->assign('order',$order);
        $this->assign('orderGoods',$orderGoods);
        $this->display();
    }
    
    /**
     * 选择搜索商品
     */
    public function zs_goods()
    {
        $brandList =  M("brand")->select();
        $categoryList =  M("goods_category")->select();
        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);      
        $where = ' store_id=0 and  is_on_sale = 1 ';//搜索条件
        I('intro')  && $where = "$where and ".I('intro')." = 1";
        
        $cat_id = I('cat_id');
        if($cat_id){            
            $goods_category = M('goods_category')->where("id = $cat_id")->find();
            $where = " $where  and cat_id{$goods_category['level']} = $cat_id "; // 初始化搜索条件
            $this->assign('cat_id',$cat_id);
        }
        if(I('brand_id')){
            $this->assign('brand_id',I('brand_id'));
            $where = "$where and brand_id = ".I('brand_id');
        }
        if(!empty($_REQUEST['keywords']))
        {
            $this->assign('keywords',I('keywords'));
            $where = "$where and (goods_name like '%".I('keywords')."%' or keywords like '%".I('keywords')."%')" ;
        } 
        $is_admin=session();
        $id=$is_admin['admin_id'];
        $roleid=M('admin')->field('role_id')->where("admin_id=$id")->find();
        $roleid=$roleid['role_id'];
        $where="$where and ty_goods.roleid=$roleid";

        $count = M('goods')->where($where)->count();
        $Page  = new AjaxPage($count,10);   
        $goodsList = M('goods')->where($where)->order('goods_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach($goodsList as $key => $val)
        {
            $spec_goods = M('spec_goods_price')->where("goods_id = {$val['goods_id']}")->select();
            $goodsList[$key]['spec_goods'] = $spec_goods;            
        }
        
        $store_bind_class = M('store_bind_class')->where("store_id =".STORE_ID)->select();
        $cat_id1 = get_arr_column($store_bind_class, 'class_1');
        $cat_id2 = get_arr_column($store_bind_class, 'class_2');
        $cat_id3 = get_arr_column($store_bind_class, 'class_3');
        $cat_id0 = array_merge($cat_id1,$cat_id2,$cat_id3);
         $show = $Page->show();
        $this->assign('cat_id0',$cat_id0);
        $this->assign('goodsList',$goodsList);
         $this->assign('page',$show);// 赋值分页输出
        $this->display();        
    }
}
